﻿Public Class frm_create_sfdl

    Const SFDLFILEVERSION As Integer = 9

    Dim _settings As New Settings

    Private _ftp_connection_info As New SFDL.File.ConnectionInfo
    Private _sfdl_files As New List(Of OLV_SFDL_Item)

    Public WriteOnly Property FTPConnectionInfo As SFDL.File.ConnectionInfo
        Set(value As SFDL.File.ConnectionInfo)
            _ftp_connection_info = value
        End Set
    End Property

    Public WriteOnly Property SFDLFiles As List(Of OLV_SFDL_Item)
        Set(value As List(Of OLV_SFDL_Item))
            _sfdl_files = value
        End Set
    End Property

    Private Sub frm_create_sfdl_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim _tools As New SFDL.Core.Tools
        Dim _settings_file_path As String
        Dim _file_save_path As String = String.Empty

        _settings = New Settings

        Try

            _settings_file_path = IO.Path.Combine(Application.StartupPath, "settings.xml")

            If IsNothing(_ftp_connection_info) Or String.IsNullOrWhiteSpace(_ftp_connection_info.Host) Then
                Throw New Exception("Fehler beim ermitteln der Verbindungseinstellungen aufgetreten!")
            End If

            If IsNothing(_sfdl_files) = True Or _sfdl_files.Count = 0 Then
                Throw New Exception("Fehler beim ermitteln der Files!")
            End If

            If IO.File.Exists(_settings_file_path) Then

                _settings = _tools.XMLDeSerialize(_settings, _settings_file_path)

                If Not String.IsNullOrEmpty(_settings.DefaultUpper) Then
                    txt_upper.Text = _settings.DefaultUpper
                End If

                If Not String.IsNullOrEmpty(_settings.DefaultDescription) Then
                    txt_desc.Text = _settings.DefaultDescription
                End If

                chk_sfdl_encrypt.Checked = _settings.DefaultEncryptionEnabled

                If Not String.IsNullOrEmpty(_settings.DefaultEncryptionPassword) Then
                    txt_sfdl_encrypt_password.Text = _settings.DefaultEncryptionPassword
                End If

                If Not String.IsNullOrEmpty(_settings.DefaultSFDLFileSaveLocation) Then
                    txt_sfdl_file_path.Text = IO.Path.Combine(_settings.DefaultSFDLFileSaveLocation, IO.Path.GetRandomFileName & ".sfdl")
                End If

                num_max_threads.Value = _settings.DefaultMaxThreads

                If _settings.GenerateFileNameWithDescription = True Then

                    If String.IsNullOrEmpty(_settings.DefaultSFDLFileSaveLocation) = False And String.IsNullOrEmpty(_settings.DefaultDescription) = False Then
                        txt_sfdl_file_path.Text = IO.Path.Combine(_settings.DefaultSFDLFileSaveLocation, _settings.DefaultDescription.Replace(Space(1), "_") & ".sfdl")
                    End If

                End If

            End If

            txt_desc.Select()

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End Sub

    Private Sub txt_desc_TextChanged(sender As Object, e As EventArgs) Handles txt_desc.TextChanged

        If Not String.IsNullOrEmpty(txt_sfdl_file_path.Text) And _settings.GenerateFileNameWithDescription = True Then

            Dim _folder_path As String = IO.Path.GetDirectoryName(txt_sfdl_file_path.Text)

            txt_sfdl_file_path.Text = IO.Path.Combine(_folder_path, txt_desc.Text.Replace(Space(1), "") & ".sfdl")

        End If

    End Sub

    Private Sub cmd_search_Click(sender As Object, e As EventArgs) Handles cmd_search.Click
        If Not SFD_SFDL.ShowDialog = Windows.Forms.DialogResult.Cancel Then
            txt_sfdl_file_path.Text = SFD_SFDL.FileName
        End If
    End Sub

    Private Sub cmd_save_Click(sender As Object, e As EventArgs) Handles cmd_save.Click

        'SFDL Datei erstellen
        Dim _new_sfdl_file As New SFDL.File.SFDLFile
        Dim _tmp_sfdl_package As New SFDL.File.SFDLPackage
        Dim _sfdl_package_list As New List(Of SFDL.File.SFDLPackage)
        Dim _tools As New SFDL.Core.Tools

        Try

            If chk_sfdl_encrypt.Checked = True And String.IsNullOrWhiteSpace(txt_sfdl_encrypt_password.Text) Then
                Throw New Exception("Wenn du die SFDL verschlüsseln willst, dann musst du ein Kennwort eingeben!")
            End If

            If IO.Directory.Exists(IO.Path.GetDirectoryName(txt_sfdl_file_path.Text)) = False Then
                Throw New Exception("Der gewählte Speicherpfad existiert nicht!")
            End If

            With _new_sfdl_file

                If _ftp_connection_info.SpecialServerMode = True Then 'Sonst gibt es Probleme mit dem Loader. Diese speziellen Einstellungen werden nur für den LIST benötigt.
                    _ftp_connection_info.ForceSingleConnection = False
                    _ftp_connection_info.DataStaleDetection = True
                End If

                .ConnectionInfo = _ftp_connection_info
                .Description = txt_desc.Text
                .Encrypted = chk_sfdl_encrypt.Checked
                .MaxDownloadThreads = num_max_threads.Value
                .SFDLFileVersion = SFDLFILEVERSION
                .Uploader = txt_upper.Text

            End With

            For Each _file In _sfdl_files

                If Not _tmp_sfdl_package.Packagename.Equals(_file.PackageName) Then 'Wenn sich packagename ändert dann neuen Package erstellen

                    If Not String.IsNullOrWhiteSpace(_tmp_sfdl_package.Packagename) Then 'nur hinzufügen wenn auch was drin ist
                        _sfdl_package_list.Add(_tmp_sfdl_package)
                    End If

                    _tmp_sfdl_package = New SFDL.File.SFDLPackage
                    _tmp_sfdl_package.Packagename = _file.PackageName
                    _tmp_sfdl_package.FileList = New List(Of File.FileInfo)
                    _tmp_sfdl_package.BulkFolderList = New List(Of File.BulkFolder)

                End If

                If _file.IsBulkFolder = False Then

                    Dim _sfdl_file_info As New SFDL.File.FileInfo

                    With _sfdl_file_info

                        .DirectoryPath = _file.DirectoryPath
                        .DirectoryRoot = _file.DirectoryRoot
                        .FileFullPath = _file.FileFullPath
                        .FileHash = _file.FileHash
                        .FileHashType = _file.FileHashType
                        .FileName = _file.FileName
                        .FileSize = _file.FileSize
                        .PackageName = _file.PackageName

                    End With

                    _tmp_sfdl_package.BulkFolderMode = False
                    _tmp_sfdl_package.FileList.Add(_sfdl_file_info)

                Else 'Bulk Folder

                    Dim _sfdl_bulk_folder_info As New SFDL.File.BulkFolder

                    With _sfdl_bulk_folder_info

                        .BulkFolderPath = _file.DirectoryPath
                        .PackageName = _file.PackageName

                    End With

                    _tmp_sfdl_package.BulkFolderMode = True
                    _tmp_sfdl_package.BulkFolderList.Add(_sfdl_bulk_folder_info)

                End If

            Next

            If Not _new_sfdl_file.Packages.Contains(_tmp_sfdl_package) Then
                _sfdl_package_list.Add(_tmp_sfdl_package)
            End If

            _new_sfdl_file.Packages = _sfdl_package_list

            If chk_sfdl_encrypt.Checked = True Then
                'SFDL noch verschlüssen
                _new_sfdl_file = EncryptSFDL(_new_sfdl_file, txt_sfdl_encrypt_password.Text)
            End If

            'SFDL DAtei schreiben
            _tools.XMLSerialize(_new_sfdl_file, txt_sfdl_file_path.Text)

            MessageBox.Show("SFDL Datei erfolgreich erstellet!", "SFDL Datei erstellt!", MessageBoxButtons.OK, MessageBoxIcon.Information)
            lbl_statusimage.Image = My.Resources.tick
            lbl_statustext.Text = "SFDL Datei erfolgreich erstellt!"

            Me.Close()

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Fehler beim erstellen der SFDL!", MessageBoxButtons.OK, MessageBoxIcon.Error)
            lbl_statustext.Text = String.Format("Fehler: {0}", ex.Message)
            lbl_statusimage.Image = My.Resources.exclamation_red
        End Try

    End Sub

    Private Function EncryptSFDL(ByVal _sfdl_file As SFDL.File.SFDLFile, ByVal _password As String) As SFDL.File.SFDLFile

        Dim _encrypted_sfdl_file As New SFDL.File.SFDLFile
        Dim _crypto As New SFDL.Crypto.AES

        With _encrypted_sfdl_file

            .Description = _crypto.EncryptString(_sfdl_file.Description, _password)
            .MaxDownloadThreads = _sfdl_file.MaxDownloadThreads
            .SFDLFileVersion = _sfdl_file.SFDLFileVersion
            .Uploader = _crypto.EncryptString(_sfdl_file.Uploader, _password)
            .Packages = New List(Of File.SFDLPackage)
            .Encrypted = True

        End With

        With _encrypted_sfdl_file.ConnectionInfo

            .DefaultPath = _crypto.EncryptString(_sfdl_file.ConnectionInfo.DefaultPath, _password)
            .Host = _crypto.EncryptString(_sfdl_file.ConnectionInfo.Host, _password)
            .Password = _crypto.EncryptString(_sfdl_file.ConnectionInfo.Password, _password)
            .Username = _crypto.EncryptString(_sfdl_file.ConnectionInfo.Username, _password)
            .AuthRequired = _sfdl_file.ConnectionInfo.AuthRequired
            .CharacterEncoding = _sfdl_file.ConnectionInfo.CharacterEncoding
            .DataType = _sfdl_file.ConnectionInfo.DataType
            .DataConnectionType = _sfdl_file.ConnectionInfo.DataConnectionType
            .EncryptionMode = _sfdl_file.ConnectionInfo.EncryptionMode
            .ListMethod = _sfdl_file.ConnectionInfo.ListMethod
            .Port = _sfdl_file.ConnectionInfo.Port

        End With

        For Each _package In _sfdl_file.Packages

            Dim _encrypted_package As New SFDL.File.SFDLPackage

            With _encrypted_package

                .Packagename = _crypto.EncryptString(_package.Packagename, _password)
                .BulkFolderMode = _package.BulkFolderMode
                .FileList = New List(Of File.FileInfo)
                .BulkFolderList = New List(Of File.BulkFolder)

            End With

            For Each _file In _package.FileList

                Dim _encrypted_file As New SFDL.File.FileInfo

                With _encrypted_file

                    .DirectoryPath = _crypto.EncryptString(_file.DirectoryPath, _password)
                    .DirectoryRoot = _crypto.EncryptString(_file.DirectoryRoot, _password)
                    .FileFullPath = _crypto.EncryptString(_file.FileFullPath, _password)
                    .FileHash = _file.FileHash
                    .FileHashType = _file.FileHashType
                    .FileName = _crypto.EncryptString(_file.FileName, _password)
                    .FileSize = _file.FileSize
                    .PackageName = _crypto.EncryptString(_file.PackageName, _password)

                End With

                _encrypted_package.FileList.Add(_encrypted_file)

            Next

            For Each _bulk_folder In _package.BulkFolderList

                Dim _encrypted_bulk_folder As New SFDL.File.BulkFolder

                With _encrypted_bulk_folder

                    .BulkFolderPath = _crypto.EncryptString(_bulk_folder.BulkFolderPath, _password)
                    .PackageName = _crypto.EncryptString(_bulk_folder.PackageName, _password)

                End With

                _encrypted_package.BulkFolderList.Add(_encrypted_bulk_folder)

            Next

            _encrypted_sfdl_file.Packages.Add(_encrypted_package)

        Next

        Return _encrypted_sfdl_file

    End Function

    Private Sub frm_create_sfdl_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown

        If e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Return Then
            cmd_save.PerformClick()
        End If

    End Sub
End Class